const express = require('express')
const router = express.Router()

const mysql = require('mysql')
// 建立连接
const db = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'mydb'
})

// // 检测链接成功与否
// db.query('select 1', (err, results) => {
//     if (err) return console.log(err.message);
//     console.log(results);
// })


router.get('/get', (req, res) => {

    // 通过req.query获取客户端通过查询字符串，发送到服务器的数据
    const query = req.query
    res.send({
        status: 0,
        msg: 'get请求成功',
        data: { name: 'zs', age: 14 }
        // data: query
    })
})


router.post('/add', (req, res) => {
    const body = req.body
    // console.log(req);
    // console.log(res);
    // // 注意问号
    const sqlStr = 'INSERT INTO user SET ?';
    db.query(sqlStr, body, (err, results) => {
        if (err) return console.log(err.message);
        if (results.affectedRows === 1) {
            console.log('插入数据成功');
        }
    })

    res.send({
        status: 0,
        msg: '添加请求成功',
        data: body
    })
})


router.post('/post', (req, res) => {
    const body = req.body

    const sql = "SELECT * FROM user WHERE username=? AND password= ?";
    db.query(sql, [body.username, body.password], (err) => {
        if (err) return res.send({
            status: 1,
            msg: 'post请求失败',
            data: body
        });
    })

    res.send({
        status: 0,
        msg: 'post请求成功',
        data: body
    })

})

module.exports = router